package com.galaxis.wms.security.handler;

import com.yvan.core.http.CookieUtils;
import com.yvan.data.redis.Redis;
import com.yvan.security.SecurityDataSource;
import com.yvan.security.config.RedisConfig;
import com.yvan.security.config.SecurityConfig;
import com.yvan.security.handler.AuthenticationFailureHandler;
import com.yvan.security.model.event.AuthenticationFailureEvent;
import com.yvan.security.utils.SecurityRedisKey;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.Ordered;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 作者：lizw <br/>
 * 创建时间：2021/12/30 21:24 <br/>
 */
public class DefaultAuthenticationFailureHandler implements AuthenticationFailureHandler {
    private final SecurityConfig securityConfig;

    public DefaultAuthenticationFailureHandler(SecurityConfig securityConfig) {
        this.securityConfig = securityConfig;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationFailureEvent event) {
        try {
            CookieUtils.delCookieForRooPath(request, response, securityConfig.getToken().getJwtTokenName());
        } catch (Exception ignored) {
        }
        final RedisConfig redis = securityConfig.getRedis();
        if (redis.isEnable() && StringUtils.isNotBlank(event.getUserId()) && event.getClaims() != null && StringUtils.isNotBlank(event.getClaims().getId())) {
            SecurityDataSource.getRedis().kExpire(
                    SecurityRedisKey.getTokenKey(redis.getRedisNamespace(), event.getUserId(), event.getClaims().getId()),
                    Redis.DEL_TIME_OUT
            );
        }
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
